package com.springboot_shopping.controller;

import com.springboot_shopping.entity.Order;
import com.springboot_shopping.entity.Payment;
import com.springboot_shopping.service.OrderService;
import com.springboot_shopping.service.PaymentService;
import com.springboot_shopping.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderService orderService;

    @PostMapping("/pay")
    public Result<String> pay(@RequestBody Payment payment, HttpSession session) {
        Order order = orderService.getById(payment.getOrderId());
        if (order.getStatus() != 1) {
            return Result.error("订单状态不可支付");
        }

        // 5. 处理支付
        boolean success = paymentService.payOrder(payment);
        if (success) {
            // 6. 更新订单状态为已支付（待发货）
            order.setStatus(2);
            order.setPayTime(payment.getPayTime());
            order.setPayType(payment.getPayTypeId()); // 设置支付方式
            orderService.updateById(order);

            return Result.success("支付成功");
        } else {
            return Result.error("支付失败");
        }
    }
}